#include "main.h"
#include "usb.hpp"
#include <stdlib.h>
#include <unistd.h>

#include "thread_msg.h"

#define CH9326_VID 0x1A86 // 0x9035 //0x1A86
#define CH9326_PID 0xE010 // 0x000A //


DevModbus::DevModbus()
{
    mqtt = new Mqtt();
    this->mqtt->Subscribe("dev/cloud_chint/dev_modbus_usb/write");
}

DevModbus::~DevModbus()
{
    if (mqtt) {
        delete mqtt;
    }
}

DevModbus *devModbus = nullptr;

int main(int argc, char** argv)
{
    std::vector<uint8_t> sBuf({ 0x03, 0x03, 0x01, 0x80, 0x00, 0x01, 0x85, 0xfc });

    sys_log_info("DEV_MODBUS_USB_VERSION = %s\n", DEV_MODBUS_USB_VERSION);

    devModbus = new DevModbus();
    if (!devModbus) {
        printf("new devModbus failed\n");
        return -1;
    }

    UsbInterface* usb = new UsbInterface();
    if (!usb) {
        printf("new usb failed\n");
        return -1;
    }

    /* mqtt消息处理线程 */
    std::thread mqtt_msg_deal_task(mqtt_msg_deal_thread);
    mqtt_msg_deal_task.detach();

    /* dev write消息处理线程 */
    std::thread dev_write_queue_deal_task(dev_write_queue_deal_thread);
    dev_write_queue_deal_task.detach();

    /* dev read消息处理线程 */
    std::thread dev_read_queue_deal_task(dev_read_queue_deal_thread);
    dev_read_queue_deal_task.detach();

    /* dev read消息处理线程 */
    std::thread dev_auto_read_queue_deal_task(dev_auto_read_queue_deal_thread);
    dev_auto_read_queue_deal_task.detach();

    while (true) 
    {
        if (usb->findUsbDevice(CH9326_VID, CH9326_PID)) 
        {
            printf("find device\n");
            if (usb->openUsbDevice()) 
            {
                printf("open success\n");
                if (usb->setTransmitParam(B9600, BIT_8, P_NONE, STOP_1, 30)) 
                {
                    printf("set param success\n");
                    if (usb->send(sBuf)) 
                    {
                        printf("send data success\n");
                        auto recvData = usb->recv();
                        if (!recvData.size()) 
                        {
                            printf("can't recv data\n");
                            usb->closeUsbDevice();
                            continue;
                        }
                        printf("recv:\n");
                        for (auto& item : recvData) {
                            printf("0x%02x, ", item);
                        }
                        printf("\n");
                        dev_read_msg_pub(recvData.at(4));
                        usb->closeUsbDevice();
                    } else {
                        printf("send data failed\n");
                        usb->closeUsbDevice();
                    }
                } else {
                    printf("set param failed\n");
                    usb->closeUsbDevice();
                }

            } else {
                printf("open failed\n");
            }

        } else {
            printf("can't find device\n");
        }

        sleep(1);
    }

    return 0;
}
